package com.hfzy.ihk.web.userCenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.facade.userCenter.entity.UserInfo;
import com.hfzy.ihk.web.oauth.client.table.PageTableHandler;
import com.hfzy.ihk.web.oauth.client.table.PageTableRequest;
import com.hfzy.ihk.web.oauth.client.table.PageTableResponse;
import com.hfzy.ihk.web.oauth.client.utils.UserUtil;
import com.hfzy.ihk.web.userCenter.biz.UserBiz;
import com.hfzy.ihk.web.userCenter.mapper.UserMapper;
import com.hfzy.ihk.web.userCenter.vo.UserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import java.sql.Wrapper;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用于集成spring security 前端控制器
 * </p>
 *
 * @author chenzesen
 * @since 2018-12-28
 */
@RestController
@RequestMapping("users")
@Slf4j
public class UserController {


    @Autowired
    UserMapper userMapper;

    @Autowired
    UserBiz userBiz;



    @RequestMapping("test")
    public String test(){
        return "成功";
    }
    /**
     * 查询用户界面
     * @param view
     * @return
     */
    @RequestMapping("userList")
    public ModelAndView saveUser(ModelAndView view) {
        view.setViewName("page/user/userList");
        return view;
    }


    /**
     * 添加用户界面
     * @param view
     * @return
     */
    @RequestMapping("addUser")
    public ModelAndView addUser(ModelAndView view) {
        view.setViewName("page/user/addUser");
        return view;
    }

    /**
     * 修改用户界面
     * @param view
     * @return
     */
    @RequestMapping("editUser")
    public ModelAndView editUser(ModelAndView view,Long id) {
        view.setViewName("page/user/editUser");
        UserInfo user = userMapper.queryUserInfo(id);
        view.addObject("user",user);
        view.addObject("id",id);
        return view;
    }

    @RequestMapping("listUsers")
    public PageTableResponse listUsers(PageTableRequest request) {
        request.setOffset((request.getOffset()-1)*request.getLimit());
        return new PageTableHandler(new PageTableHandler.CountHandler() {

            @Override
            public int count(PageTableRequest request) {

                return userMapper.count(request.getParams());
            }
        }, new PageTableHandler.ListHandler() {

            @Override
            public List<UserInfo> list(PageTableRequest request) {
                List<UserInfo> list = userMapper.list(request.getParams(), request.getOffset(), request.getLimit());
                return list;
            }
        }).handle(request);
    }

    /**
     * 保存用户
     * @param userDto
     * @return
     */
    @RequestMapping("saveUser")
    public Map<String,Object> saveUser( UserInfoDto userDto) {
        Map<String,Object> map = new HashMap<>();
        try {
            userBiz.saveUser(userDto);
            map.put("code",1);
            map.put("msg","保存成功");
        }catch (IllegalArgumentException e1){
            log.error("保存用户失败{}",userDto.getUsername(),e1);
            map.put("code",0);
            map.put("msg",e1.getMessage());

        }catch (Exception e){
            log.error("保存用户失败{}",userDto.getUsername(),e);
            map.put("code",0);
            map.put("msg","保存失败");
        }
        return map;
    }


    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("deleteUser")
    public Map<String,Object> deleteUser(Long id,String enabled) {
        Map<String,Object> map = new HashMap<>();
        try {
            userMapper.updateEnabledById(id,enabled);
            map.put("code",1);
            map.put("msg","删除成功");
        }catch (Exception e){
            map.put("code",0);
            map.put("msg","操作失败");
            log.error("删除用户失败~",e);
        }
        return map;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("validUser")
    public Map<String,Object> validUser(Long id,String enabled) {
        Map<String,Object> map = new HashMap<>();
        try {
            userMapper.updateEnabledById(id,enabled);
            map.put("code",1);
            map.put("msg","删除成功");
        }catch (Exception e){
            map.put("code",0);
            map.put("msg","操作失败");
            log.error("删除用户失败~",e);
        }
        return map;
    }


    /**
     * 修改密码界面
     * @param view
     * @return
     */
    @RequestMapping("changePasswordList")
    public ModelAndView changePasswordList(ModelAndView view) {
        UserInfo user = UserUtil.getLoginUser();
        view.addObject("username",user.getUsername());
        view.setViewName("page/user/password");
        return view;
    }



    @RequestMapping("changePassword")
    public Map<String,Object> changePassword(String username, String oldPassword, String newPassword, String cofirmPassword) {
        Map<String,Object> map = new HashMap<>();
        try {
            String rs =  userBiz.changePassword(username, oldPassword, newPassword);
            map.put("msg",rs);

        }catch (Exception e){
            log.error("修改密码错误",e);
            map.put("msg","修改密码错误");
        }
        log.info(">>>>>>>>>>修改密码返回结果：{}",map.toString());
        return map;
    }

    /**
     * 通过组别或者部门或者团队 加上工号名字搜索人员
     * @param userName
     * @return
     */
    @RequestMapping("selectUserList")
    public List<UserInfo> selectUserList(String userName){
        try {
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
            queryWrapper.like("username",userName);
            return userMapper.selectList(queryWrapper);
        } catch (Exception e) {
            log.error("异常：",e);
        }
        return new ArrayList<>();
    }

    @RequestMapping("queryUserListByIds/{uids}")
    public List<UserInfo> queryUserListByIds(@PathVariable String uids){
        if(!Utils.isNullString(uids)){
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
            queryWrapper.in("id", Arrays.asList(uids.split(",")));
            return userMapper.selectList(queryWrapper);
        }else{
            return new ArrayList<>();
        }
    }

    @RequestMapping("querySimpleUserInfo/{uids}")
    public List<UserInfo> querySimpleUserInfo(@PathVariable String uids){
        if(!Utils.isNullString(uids)){
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
            queryWrapper.in("id", Arrays.asList(uids.split(",")));
            List<UserInfo> userInfos = new ArrayList<>();
            List<Integer> ids = Arrays.stream(uids.split(",")).map(it->Integer.parseInt(it)).collect(Collectors.toList());
            return userBiz.querySimpleUserInfo(ids);
        }else{
            return new ArrayList<>();
        }
    }


}
